from pyecharts import options as opts
from pyecharts.charts import Sankey
from influxdb import InfluxDBClient

# 定义节点
nodes = [
    {"name": "吉行生活"},
    # {"name": "领克"},
    {"name": "登录"},
    {"name": "商情"},
    {"name": "登录-离开"},
    {"name": "下单"},
    {"name": "支付"},
    {"name": "下单-离开"},
    {"name": "商情-离开"},
]

client = InfluxDBClient(host='10.240.52.133', port=31521, username='admin', password='admin',
                        database='businessanalysis')

# 编写查询语句
query = """select count("uid") from customer_operation where "type"='LOGIN'"""
login = 0
result = client.query(query)
for point in result.get_points():
    login = point["count"]
    print(f'Time: {point["time"]}, Value: {point["count"]}')
PRODUCT_DETAILS = 0
result = client.query(
    """select count(uid) from (SELECT *  FROM "customer_operation" WHERE "type"='PRODUCT_DETAILS' group by "linkUid")""")
for point in result.get_points():
    PRODUCT_DETAILS = point["count"]
PLACE_ORDER = 0
result = client.query(
    """select count(uid) from (SELECT *  FROM "customer_operation" WHERE "type"='PLACE_ORDER' group by "linkUid")""")
for point in result.get_points():
    PLACE_ORDER = point["count"]
PAY = 0
result = client.query(
    """select count(uid) from (SELECT *  FROM "customer_operation" WHERE "type"='PAY' group by "linkUid")""")
for point in result.get_points():
    PAY = point["count"]

# 定义链接和流量
links = [
    {"source": "吉行生活", "target": "登录", "value": login},
    # {"source": "领克", "target": "登录", "value": 20},
    {"source": "登录", "target": "商情", "value": PRODUCT_DETAILS},
    {"source": "登录", "target": "登录-离开", "value": login - PRODUCT_DETAILS},
    {"source": "商情", "target": "下单", "value": PLACE_ORDER},
    {"source": "商情", "target": "商情-离开", "value": PRODUCT_DETAILS - PLACE_ORDER},
    {"source": "下单", "target": "支付", "value": PAY},
    {"source": "下单", "target": "下单-离开", "value": PLACE_ORDER - PAY},
]

# 创建桑基图对象
sankey = Sankey()

# 添加节点和连接关系
sankey.add(
    "用户行为流",  # 标题
    nodes,  # 节点数据
    links,  # 链接数据
    linestyle_opt=opts.LineStyleOpts(opacity=0.2, curve=0.5, color="source"),
    label_opts=opts.LabelOpts(position="right"),
)

# 设置全局配置项
sankey.set_global_opts(
    title_opts=opts.TitleOpts(title="桑基图示例"),
    tooltip_opts=opts.TooltipOpts(trigger="item", trigger_on="mousemove"),
)

# 渲染到HTML文件
sankey.render("sankey_demo.html")
